import { Button, DotLoading, Grid, NavBar, Space } from 'antd-mobile';
import React, { useEffect, useState } from 'react';

import { Content, Page } from '@alita/flow';
import {
  setPageNavBar,
  useLocation,
  useNavigate,
  useSearchParams,
} from 'alita';

import { DemoBlock } from '@/components/demos-util';
import { checkAuthorize } from '@/utils/authorize';
import { getRequestInit, urlPrefix } from '@/utils/http';

import type { DetailResult } from '@/pages/types/type';

import StaffLivings from '@/components/object-staff-living';

import { PickerUpdatePopup } from '@/components/update';
import { OASystem } from '@/pages/types/type';
import { useModel } from 'alita';
import styles from './index.less';

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(5);
  const model = useModel('useAuthModel');
  // 普通常规states定义结束
  const [detail, setDetail] = useState<OASystem>(); // 加载系统对象信息

  // 从参数中读取到的变量
  const sid = searchParams.get('id'); // 传入参数变量
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `系统授权`,
        pageBackground: '#eee',
      },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log('token检查完成！y=', y);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 1;
      // 加载系统对象信息 // 代码生成annotations.utils.TsCodeCreator
      const mzcer = `/api/oa-system-detail/get/${sid}`;
      let mzcerResponse: Promise<Response> = fetch(
        `${urlPrefix}${mzcer}`,
        getRequestInit(),
      );
      mzcerResponse
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(async ({ data, code, msg }: DetailResult<OASystem>) => {
                if (code === 0) {
                  setLoadOK(msg);
                  setDetail(data);
                  console.log('set dataOK!');
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              })
              .finally(() => {
                console.log(`${mzcer} inner finally!`);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `请求${mzcer}时发生错误：${reason}`]);
        })
        .finally(() => {
          console.log(`${mzcer} outter finally!`);
          setLoadingTimes(--times);
        });
    } // end if authOK
  }
  useEffect(load, [authOK, sid]);

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入，还有{loadingTimes}个请求...</span>
      </div>
    );
  }

  console.log('detail', detail);
  const {
    id,
    performanceChartPeriod,
    paidChartPeriod,
    performancePayStage,
    paidRewardPayStage,
    canUseInvoicePocket,
  } = detail!;

  return (
    <Page>
      <Content>
        <div className={styles.header}>
          <DemoBlock padding={8}>
            <NavBar
              left={
                <Button
                  color="primary"
                  size="mini"
                  shape="rounded"
                  onClick={() => navigate('/')}
                >
                  首
                </Button>
              }
              right={
                <div style={{ fontSize: 24 }}>
                  <Space style={{ '--gap': '16px' }}>
                    <Button
                      color="primary"
                      size="mini"
                      shape="rounded"
                      onClick={() => {
                        navigate(
                          `/object-staff-living/create?url=oa-system-staff-living&origin=1`,
                        );
                      }}
                    >
                      去授权
                    </Button>
                  </Space>
                </div>
              }
              onBack={() => navigate(-1)}
            >
              系统设置
            </NavBar>
          </DemoBlock>
        </div>

        <DemoBlock padding={8} marginTop="12px">
          <Grid columns={2} gap={3} style={{ marginTop: '8px' }}>
            <Grid.Item>
              <Space wrap>
                商机新签收款默认统计周期：
                {paidChartPeriod.label}
                <PickerUpdatePopup
                  itemsFromUrl="/api/enums/date-periods/values"
                  onSuccess={load}
                  origin={id}
                  title="商机新签收款默认统计周期"
                  current={paidChartPeriod}
                  url="/api/oa-system-paid-chart-period-history"
                />
              </Space>
            </Grid.Item>
            <Grid.Item>
              <Space wrap>
                产值默认统计周期：{performanceChartPeriod.label}
                <PickerUpdatePopup
                  itemsFromUrl="/api/enums/date-periods/values"
                  onSuccess={load}
                  origin={id}
                  title="产值默认统计周期"
                  current={performanceChartPeriod}
                  url="/api/oa-system-performance-chart-period-history"
                />
              </Space>
            </Grid.Item>
          </Grid>
          <Grid columns={2} gap={3} style={{ marginTop: '8px' }}>
            <Grid.Item>
              <Space wrap>
                技术绩效支付批次：{performancePayStage?.label}
                <PickerUpdatePopup
                  itemsFromUrl="/api/performance-pay-stage-rel/str-tree"
                  onSuccess={load}
                  origin={id}
                  title="修改当前使用技术绩效支付批次"
                  current={performancePayStage}
                  url="/api/oa-system-pay-stage-history"
                />
              </Space>
            </Grid.Item>
            <Grid.Item>
              <Space wrap>
                业务绩效支付批次：{paidRewardPayStage?.label}
                <PickerUpdatePopup
                  itemsFromUrl="/api/performance-pay-stage-rel/str-tree"
                  onSuccess={load}
                  origin={id}
                  title="修改业务绩效支付批次"
                  current={paidRewardPayStage}
                  url="/api/oa-system-paid-reward-pay-stage-history"
                />
              </Space>
            </Grid.Item>
          </Grid>
          <Grid columns={2} gap={3} style={{ marginTop: '8px' }}>
            <Grid.Item>
              <Space wrap>是否支持使用票池：{canUseInvoicePocket?"是":"否"}</Space>
            </Grid.Item>
          </Grid>
        </DemoBlock>

        <DemoBlock padding={8} marginTop="12px">
          <StaffLivings
            includeDescendants={false}
            url="oa-system-staff-living"
            origin={id}
          />
        </DemoBlock>
      </Content>
    </Page>
  );
};
